// API请求封装
export const BASE_URL = 'https://shop.msicdz.com/' // 请替换为您的实际API域名

class Request {
  constructor() {
    this.baseURL = BASE_URL
    this.timeout = 10000
  }

  // 获取token
  getToken() {
    return uni.getStorageSync('token') || ''
  }

  // 设置token
  setToken(token) {
    uni.setStorageSync('token', token)
  }

  // 清除token
  clearToken() {
    uni.removeStorageSync('token')
  }

  // 请求拦截器
  interceptRequest(config) {
    // 添加token
    const token = this.getToken()
    if (token) {
      config.header = {
        ...config.header,
        'Authorization': `Bearer ${token}`
      }
    }

    // 添加通用header
    config.header = {
      ...config.header,
      'Content-Type': 'application/json'
    }

    return config
  }

  // 响应拦截器
  interceptResponse(response) {
    const { statusCode, data } = response
    console.log(data)
    console.log(statusCode)
    // HTTP状态码检查
    if (statusCode === 200) {
      // 业务状态码检查
      if (data.code === 1 || data.code === 200) {
        return new Promise((resolve, reject) => {
          resolve(data)
        })
      } else if (data.code === 401) {
        // token过期，清除本地token并跳转登录
        this.clearToken()
        return Promise.reject(new Error(data.msg || '登录已过期'))
      } else {
        uni.showToast({
          title: data.msg || '请求失败',
          icon: 'none'
        })
        return Promise.reject(new Error(data.msg || '请求失败'))
      }
    } else {
      uni.showToast({
        title: data.msg || '网络请求失败',
        icon: 'none'
      })
      return Promise.reject(new Error('网络请求失败'))
    }
  }

  // 通用请求方法
  request(options) {
    return new Promise((resolve, reject) => {
      // 请求拦截
      const config = this.interceptRequest({
        url: (options.baseURL || this.baseURL) + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: options.header || {},
        timeout: options.timeout || this.timeout
      })

      uni.request({
        ...config,
        success: (response) => {
          this.interceptResponse(response)
            .then(resolve)
            .catch(reject)
        },
        fail: (error) => {
          uni.showToast({
            title: '网络连接失败',
            icon: 'none'
          })
          reject(error)
        }
      })
    })
  }

  // GET请求
  get(url, params = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data: params,
      ...options
    })
  }

  // POST请求
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  // PUT请求
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  // DELETE请求
  delete(url, params = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data: params,
      ...options
    })
  }

  // 文件上传
  upload(url, filePath, formData = {}, options = {}) {
    return new Promise((resolve, reject) => {
      const token = this.getToken()
      const header = {}

      if (token) {
        header['Authorization'] = `Bearer ${token}`
      }

      uni.uploadFile({
        url: this.baseURL + url,
        filePath,
        name: 'file',
        formData,
        header,
        success: (response) => {
          try {
            const data = JSON.parse(response.data)
            this.interceptResponse({
              statusCode: response.statusCode,
              data
            }).then(resolve).catch(reject)
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }
}

// 创建实例
const request = new Request()

export default request
